// 59. 螺旋矩阵 II
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ret(n, vector<int>(n));
        int left = 0, right = n-1, top = 0, bottom = n-1;
        int num = 0;
        while(true)
        {
            for(int i = left; i <= right; ++i) ret[top][i] = ++num;
            if(++top > bottom) break;
            for(int i = top; i <= bottom; ++i) ret[i][right] = ++num;
            if(--right < left) break;
            for(int i = right; i >= left; --i) ret[bottom][i] = ++num;
            if(--bottom < top) break;
            for(int i = bottom; i >= top; --i) ret[i][left] = ++num;
            if(++left > right) break;
        }
        
        return ret;
    }
};

// 581. 最短无序连续子数组
class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> tmp(nums);
        sort(tmp.begin(), tmp.end());
        if(tmp == nums) return 0;

        int n = nums.size();
        int ln = 0, rn = 0;
        for(int i = 0; i < n; ++i)
        {
            if(nums[i] != tmp[i])
            {
                ln = i;
                break;
            }
        }
        for(int i = n-1; i >=0; --i)
        {
            if(nums[i] != tmp[i])
            {
                rn = i;
                break;
            }
        }
        return rn - ln + 1;
    }
};